<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CreateOrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            // 地址相关
            'address_id' => ['required', 'integer', 'exists:user_addresses,id'],
            
            // 支付相关
            'payment_method' => [
                'nullable',
                'string',
                Rule::in(['alipay', 'wechat', 'cod'])
            ],
            
            // 优惠券相关
            'user_coupon_id' => ['nullable', 'integer', 'exists:user_coupons,id'],
            
            // 备注
            'notes' => ['nullable', 'string', 'max:500'],
            
            // 购物车结算和立即购买都不需要传递商品数据
            // 商品数据分别来自购物车和session
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'address_id.required' => '请选择收货地址',
            'address_id.exists' => '收货地址不存在',
            
            'payment_method.required' => '请选择支付方式',
            'payment_method.in' => '支付方式无效',
            
            'user_coupon_id.exists' => '优惠券不存在或已失效',
            
            'notes.max' => '备注不能超过500个字符',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'address_id' => '收货地址',
            'payment_method' => '支付方式',
            'user_coupon_id' => '优惠券',
            'notes' => '备注',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // 验证地址是否属于当前用户
            if ($this->filled('address_id')) {
                $address = \App\Models\UserAddress::find($this->address_id);
                if ($address && $address->user_id !== auth()->id()) {
                    $validator->errors()->add('address_id', '收货地址不属于当前用户');
                }
            }
            
            // 验证优惠券是否属于当前用户
            if ($this->filled('user_coupon_id')) {
                $userCoupon = \App\Models\UserCoupon::find($this->user_coupon_id);
                if ($userCoupon && $userCoupon->user_id !== auth()->id()) {
                    $validator->errors()->add('user_coupon_id', '优惠券不属于当前用户');
                }
            }
            
        });
    }
}
